package com.itheima.reggie.controller;



import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
public class FileController {

    @Value("${fileDir}")
    private String fileDirPath;

    /**
     * 文件上传
     * @param file 页面上传上来的文件对象
     * @return
     */
    @PostMapping("/common/upload")
    public R upload(MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String preffix = UUID.randomUUID().toString().replaceAll("-" , "");

        String newName = preffix + suffix;

        File fileDir = new File(fileDirPath);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }

        file.transferTo(new File(fileDir , newName ));

        return R.success(newName);
    }

    /**
     * 文件下载
     * @param name
     * @return
     */
    @GetMapping("/common/download")
    public void download(String name , HttpServletResponse resp) throws Exception {
        String file = fileDirPath + name;

        FileInputStream fis = new FileInputStream(file);


        ServletOutputStream os = resp.getOutputStream();


        IOUtils.copy(fis, os);


    }
}

